package com.koala.mylittlesecretary;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;

public class ContactReader {

	public ContactItems readContacts() {
		Log.v("MLS", "Reading contacts..");

		ContactItems myCI = new ContactItems(this.getCountryCode());

		Cursor cursor = MainActivity.mainAct.getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			String contactId = cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts._ID));
			String hasPhone = cursor
					.getString(cursor
							.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

			if (hasPhone.contentEquals("1")) {
				// You know it has a number so now query it like this

				Cursor phones = MainActivity.mainAct
						.getContentResolver()
						.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
								null,
								ContactsContract.CommonDataKinds.Phone.CONTACT_ID
										+ " = " + contactId, null, null);

				while (phones.moveToNext()) {
					String contactName = phones
							.getString(phones
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

					String phoneNumber = phones
							.getString(phones
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					myCI.addNewElement(contactName, phoneNumber);
				}
				phones.close();
			}

			/*
			 * Cursor emails = myAct.getContentResolver().query(
			 * ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
			 * ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " +
			 * contactId, null, null); while (emails.moveToNext()) { // This
			 * would allow you get several email addresses String emailAddress =
			 * emails .getString(emails
			 * .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); //
			 * Log.v("MLS", emailAddress); } emails.close();
			 */

		}
		cursor.close();
		return myCI;
	}

	private int getCountryCode() {
		TelephonyManager tm;
		tm = (TelephonyManager) MainActivity.mainAct.getBaseContext()
				.getSystemService(Context.TELEPHONY_SERVICE);
		String loc = tm.getSimCountryIso().trim();
		if (loc.equals("de")) {
			Log.v("MLS", "Country Code: de");
			return 49;
		} else {
			Log.e("MLS", "Unknown Country Code: " + loc);
			return 0;
		}

	}

	public ContactReader() {
		Log.v("MLS", "ContactReader initialized");
	}

}
